import java.io.*;
import java.util.Scanner;

public class demo13 {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("输入你要扫描的目录");
        String DirPath = scanner.next();
        File dirFile = new File(DirPath);
        if(!dirFile.isDirectory()){
            System.out.println("输入的路径不是目录,退出");
            return;
        }
        System.out.println("输入关键值");
        String  keyWord = scanner.next();
        scanFile(dirFile,keyWord);
    }

    private static void scanFile(File dirFile, String keyWord) throws IOException {
        File[] files = dirFile.listFiles();
        for(File file : files) {
            if (file.isFile()) {
                dealFile(file,keyWord);
            }else {
                //是目录就继续扫描目录
                scanFile(file,keyWord);
            }
        }
    }

    private static void dealFile(File file, String keyWord) throws  IOException {
        //扫描名字看看是否含有关键字
        if(file.getName().contains(keyWord)){
            System.out.println("找到一个文件"+file.getAbsoluteFile());
        }
        //扫描内容看看是否含有关键字
        StringBuffer stringBuffer = new StringBuffer();
        try(Reader reader = new FileReader(file)){
            while(true){
                char[] buff = new char[1024];
                int t = reader.read(buff);
                if(t==-1){
                    break;
                }
                stringBuffer.append(buff,0,t);
            }
        }
        if(stringBuffer.indexOf(keyWord)>=0){
            System.out.println("找到一个符合要求的文件"+file.getAbsoluteFile());
        }
    }

}
